﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace CMS.REST
{
    /// <summary>
    /// CMS后端统一的返回格式
    /// </summary>
    public class RESTResponse
    {
        /// <summary>
        /// 返回数据
        /// </summary>
        [JsonProperty(PropertyName = "data")]
        public JArray Data { get; set; }

        /// <summary>
        /// 执行状态
        /// </summary>
        [JsonProperty(PropertyName = "status")]
        public int Status { get; set; }

        /// <summary>
        /// 错误信息描述
        /// </summary>
        [JsonProperty(PropertyName = "errmsg")]
        public string ErrMsg { get; set; }

        /// <summary>
        /// 检查是否表示成功的响应(检查状态码是否为200)
        /// </summary>
        [JsonIgnore]
        public bool IsSuccess => Status == 200;

        public RESTResponse() { }

        /// <summary>
        /// 通过一个异常生成一个反馈
        /// </summary>
        /// <param name="exception"></param>
        public RESTResponse(Exception exception)
        {
            Data = new JArray();
            Status = 500;
            ErrMsg = exception.Message;
        }

        public override string ToString()
        {
            return $"{{{nameof(RESTResponse)}[{Status}]:{Data.ToString()}}}";
        }
    }
}
